<template>
  <el-drawer
    title="派单"
    v-model="visible"
    size="60%"
    direction="rtl"
    :with-header="true"
    :before-close="beforeClose"
  >
    <el-card class="box-shadow">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="工单类型" prop="type">
          <el-radio-group v-model="formData.type" @change="handleTypeChange">
            <el-radio-button
              v-for="item in typeList"
              :key="item.type"
              :label="item.type"
            >
              {{ item.type }}
            </el-radio-button>
          </el-radio-group>
        </el-form-item>

        <el-card class="box-shadow">
          <template #header>
            <div class="clearfix">
              <span>明细数据</span>
              <span style="float: right; padding: 3px 0">工单总分值：{{ score }} </span>
            </div>
          </template>
          <el-table :data="detailsList" style="width: 100%">
            <el-table-column prop="name" label="内容" min-width="25%"/>
            <el-table-column prop="columnDesc" label="描述" min-width="30%"/>
            <el-table-column prop="scope" label="对应分值" min-width="10%">
              <template #default="scope">
                {{ scope.row.score + '分' }}
              </template>
            </el-table-column>
            <el-table-column prop="demandNum" label="数量" min-width="15%">
              <template #default="scope">
                <el-input-number
                  :min="0"
                  v-model="scope.row.demandNum"
                  :step="1"
                  @change="handleNumChange($event, scope.$index)"
                  placeholder="请输入数量"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <el-divider/>

        <el-row :gutter="20">
          <el-col :span="16">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="formData.productName" placeholder="请输入产品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="formData.productCode" placeholder="请输入产品编码"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="10">
            <el-form-item label="优先级" prop="priority" v-if="formData.type !== '视觉-快速散图'">
              <el-radio-group v-model="formData.priority">
                <el-radio
                  v-for="dict in getDictOptions(DICT_TYPE.BUSINESS_PRIORITY)"
                  :key="dict.value"
                  :label="dict.label"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="派单人员" prop="sendUserId">
              <cascader-user v-model="formData.sendUserId" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="派单部门" prop="sendDeptId">
              <cascader-dept v-model="formData.sendDeptId" disabled/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="需求描述" prop="demandDesc">
          <editor v-model="formData.demandDesc" placeholder="请输入内容" :height="300"/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="需求图片" prop="demandImg">
              <upload-imgs v-model="formData.demandImg"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="需求附件" prop="demandFile">
              <upload-file v-model="formData.demandFile"/>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="预计完成时间" prop="sendEndDatetime">
              <el-date-picker
                v-model="formData.sendEndDatetime"
                type="date"
                value-format="x"
                placeholder="选择发起预计处理完成时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <div class="drawer-footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </div>
  </el-drawer>
</template>


<script setup>
import {computed, reactive, ref} from 'vue'
import {FormInfoApi} from '@/api/business/general/form'
import {VisualOrderApi} from '@/api/business/design/visual'
import {useUserStore} from "@/store/modules/user";
import {DICT_TYPE, getDictOptions} from "@/utils/dict";

const message = useMessage() // 消息弹窗

const userStore = useUserStore()

// 响应式数据
const visible = ref(false)
const formRef = ref()
const formData = ref({
  id: undefined,
  remark: undefined,
  type: '',
  score: undefined,
  addScore: undefined,
  details: undefined,
  productName: undefined,
  productCode: undefined,
  sendUserId: '',
  sendDeptId: '',
  sendEndDatetime: undefined,
  state: undefined,
  priority: undefined,
  demandDesc: undefined,
  demandImg: undefined,
  demandFile: '',
  takeEndDatetime: undefined,
  deliveryUserId: undefined,
  deliveryDatetime: undefined,
  takeDatetime: undefined,
  takeUserId: undefined,
  finishResult: undefined,
  finishImg: undefined,
  finishFile: undefined,
  finishDatetime: undefined,
  outTrackId: undefined,
  auditResult: undefined,
  auditUserId: undefined,
  auditRemark: undefined,
  auditDatetime: undefined
})

const typeList = ref([])
const detailsList = ref([])


// 计算属性
const score = computed(() => {
  let total = 0
  detailsList.value.forEach(item => {
    total += item.score * item.demandNum
  })
  return Number(total.toFixed(2))
})

// 表单规则
const rules = reactive({
  type: [
    {required: true, message: '请选择工单类型', trigger: 'blur'}
  ],
  productName: [
    {required: true, message: '请填写产品名称', trigger: 'blur'}
  ],
  priority: [
    {required: true, message: '请选择优先级', trigger: 'blur'}
  ],
  sendDeptId: [
    {required: true, message: '请选择派单人员', trigger: 'blur'}
  ],
  sendUserId: [
    {required: true, message: '请选择派单部门', trigger: 'blur'}
  ],
  demandDesc: [
    {required: true, message: '请填写需求描述', trigger: 'blur'}
  ],
  productCode: [
    {required: true, message: '请填写产品编码', trigger: 'blur'}
  ],
  demandImg: [
    {required: true, message: '请填写图片需求', trigger: 'blur'}
  ]
})


const showVisible = () => {
  resetForm()
  formData.value.sendDeptId = userStore.user.deptId.toString()
  formData.value.sendUserId = userStore.user.id.toString()
  getTypeFormInfo()
  formData.value.type = '视觉-快速散图'
  handleTypeChange('视觉-快速散图')
}
defineExpose({showVisible}) // 提供 open 方法，用于打开弹窗
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const getTypeFormInfo = () => {
  FormInfoApi.getFormInfoPage({module: 'visual'}).then(res => {
    typeList.value = res.list
    visible.value = true
  })
}

const handleTypeChange = (val) => {
  FormInfoApi.getFormDetailsListByType(val).then(res => {
    detailsList.value = res.map(item => ({
      name: item.name,
      columnDesc: item.columnDesc,
      score: item.score,
      demandNum: 0
    }))
  })
}

const beforeClose = (done) => {
  message.confirm('确认取消提交吗？')
    .then(() => {
      done()
    })
    .catch(() => {
      // 取消关闭
    })
}

const submitForm = async () => {
  await formRef.value.validate()

  if (score.value === 0) {
    message.error('工单分值为0，请检查！！！')
    return
  }

  if (formData.value.type === '视觉-快速散图') {
    formData.value.priority = ''
  }
  // 处理需求图片（数组转字符串）
  if (Array.isArray(formData.value.demandImg)) {
    formData.value.demandImg = formData.value.demandImg.join(',')
  }
  // 处理需求附件（数组转字符串）
  if (Array.isArray(formData.value.demandFile)) {
    formData.value.demandFile = formData.value.demandFile.join(',')
  }

  formData.value.score = score.value
  formData.value.details = JSON.stringify(detailsList.value)

  if (formData.value.id) {
    // updateVisualInfo(formData.value).then(() => {
    //   message.success('修改成功')
    //   visible.value = false
    //   emit('refresh')
    // })
  } else {
    VisualOrderApi.createVisualOrder(formData.value).then(() => {
      message.success('新增成功')
      visible.value = false
      emit('success')
    })
  }


}

const handleNumChange = (value, index) => {
  // 确保 value 是数字且不小于 0
  if (value === null || isNaN(value)) {
    value = 0;
  }
  detailsList.value[index].demandNum = Math.floor(value);
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    remark: undefined,
    type: undefined,
    score: undefined,
    addScore: undefined,
    details: undefined,
    productName: undefined,
    productCode: undefined,
    sendUserId: undefined,
    sendDeptId: undefined,
    sendEndDatetime: undefined,
    state: undefined,
    priority: undefined,
    demandDesc: undefined,
    demandImg: undefined,
    demandFile: undefined,
    takeEndDatetime: undefined,
    deliveryUserId: undefined,
    deliveryDatetime: undefined,
    takeDatetime: undefined,
    takeUserId: undefined,
    finishResult: undefined,
    finishImg: undefined,
    finishFile: undefined,
    finishDatetime: undefined,
    outTrackId: undefined,
    auditResult: undefined,
    auditUserId: undefined,
    auditRemark: undefined,
    auditDatetime: undefined
  }
  formRef.value?.resetFields()
}


</script>

<style scoped>
.drawer-footer {
  text-align: right;
  margin-top: 20px;
}

.drawer-footer button {
  margin-left: 10px;
}

.clearfix {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>

